package com.lagou.Title4;

import org.w3c.dom.ls.LSOutput;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class MyClient {

    //运行客户端的静态方法
    public static void run(){
        //定义变量名
        Scanner sc = null;
        Socket socket = null;
        ObjectOutputStream objectOutputStream = null;
        ObjectInputStream objectInputStream = null;
        UserMessage userMessage = null;
        try {
            //创建Socket类型的对象并提供服务器的主机名和端口号
            socket = new Socket("127.0.0.1",8888);
            System.out.println("成功连接服务器！");

            //初始化输入输出流
            sc = new Scanner(System.in);
            objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectInputStream = new ObjectInputStream(socket.getInputStream());

            //从控制台获取用户的输入信息
            User user = new User();
            System.out.print("请输入用户名：");
            user.setUsername(sc.next().strip());
            System.out.print("请输入密码：");
            user.getPassword(sc.next().strip());

            //发送用户信息给服务器
            objectOutputStream.writeObject(new UserMessage("check",user));
            System.out.println("已发送用户信息到服务器！");

            //读取服务端回发的验证结果
            try {
                userMessage = (UserMessage) objectInputStream.readObject();
                System.out.println("从服务器收到验证结果为：" + userMessage);
            }catch (ClassNotFoundException e){
                e.printStackTrace();
            }
            //根据验证结果输出的提示到控制台
            if (userMessage != null){
                if ("success".equals(userMessage.getType())){
                    System.out.println("登陆成功！");
                }else if("fail".equals(userMessage.getType())){
                    System.out.println("登陆失败！");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流并释放有关的资源
            System.out.println("服务器断开连接！");
            if (objectInputStream != null) {
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (objectOutputStream != null){
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (sc != null) {
                sc.close();
            }
        }
    }

    public static void main(String[] args) {
        run();
    }
}
